package top.someapp.applib.kits;

import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * @author zwz
 * Created on 2020-03-30
 */
public class Booleans {

    private Booleans() {
        // no need instance.
    }

    public static boolean cStyleBoolean(Number number) {
        if (number == null) {
            return false;
        }
        if (number instanceof Byte) {
            return number.byteValue() != 0;
        }
        if (number instanceof Short) {
            return number.shortValue() != 0;
        }
        if (number instanceof Integer) {
            return number.intValue() != 0;
        }
        if (number instanceof Long) {
            return number.longValue() != 0;
        }
        if (number instanceof Float) {
            return number.floatValue() != 0;
        }
        if (number instanceof Double) {
            return number.doubleValue() != 0;
        }
        if (number instanceof BigInteger) {
            return !BigInteger.ZERO.equals(number);
        }
        if (number instanceof BigDecimal) {
            return !BigDecimal.ZERO.equals(number);
        }
        throw new ClassCastException("Unsupport type: " + number.getClass().getName());
    }

    public static boolean parse(String value) {
        return "true".equalsIgnoreCase(value);
    }

    public static boolean and(boolean... booleans) {
        boolean breakOut = false;
        for (boolean b : booleans) {
            if (!b) {
                breakOut = true;
                break;
            }
        }
        return not(breakOut);
    }

    public static boolean or(boolean... booleans) {
        boolean breakOut = false;
        for (boolean b : booleans) {
            if (b) {
                breakOut = true;
                break;
            }
        }
        return breakOut;
    }

    public static boolean not(boolean b) {
        return !b;
    }

    public static boolean trueTrue(boolean first, boolean second) {
        return first & second;
    }

    public static boolean falseFalse(boolean first, boolean second) {
        return (!first) & (!second);
    }

    public static boolean trueFalse(boolean first, boolean second) {
        if (first) {
            return !second;
        }
        return false;
    }

    public static boolean falseTrue(boolean first, boolean second) {
        if (!first) {
            return second;
        }
        return false;
    }

    public static boolean allTrue(boolean... booleans) {
        return and(booleans);
    }

    public static boolean allFalse(boolean... booleans) {
        return not(or(booleans));
    }

    public static <T> T iif(boolean test, T valueIfTrue, T valueIfFalse) {
        if (test) {
            return valueIfTrue;
        }
        return valueIfFalse;
    }
}
